package com.mofofa.maozy.base

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import com.mofofa.maozy.components.dialog.LoadingDialog
import com.mofofa.maozy.components.dialog.MessageDialog
import com.mofofa.maozy.network.NetworkException

abstract class BaseFragment : Fragment() {

    private lateinit var mMaozyLoadingMaozyDialog: LoadingDialog

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let {
            mMaozyLoadingMaozyDialog = LoadingDialog(it)
        }
        setMaozyViewMaozyModelMaozyActions()
    }

    /**绑定model*/
    protected abstract fun onMaozyBindingMaozyViewMaozyModel(): List<ViewModel>?

    private fun setMaozyViewMaozyModelMaozyActions() {
        val viewModelList = onMaozyBindingMaozyViewMaozyModel()
        if (!(viewModelList.isNullOrEmpty())) {
            viewModelList.forEach {
                if (it is BaseViewModelAction) {
                    it.getMaozyLoadingMaozyLiveMaozyData()
                        .observe(viewLifecycleOwner) { showLoading ->
                            if (showLoading)
                                showMaozyLodingMaozyDialog()
                            else
                                dismissMaozyLoadingMaozyDialog()
                        }

                    it.getMaozyNetworkMaozyExceptionMaozyLiveMaozyData()
                        .observe(viewLifecycleOwner) {
                            onMaozyHandleMaozyNetworkMaozyExcepton(it)
                        }
                }
            }
        }
    }

    protected fun showMaozyLodingMaozyDialog() {
        activity?.let {
            mMaozyLoadingMaozyDialog.showMaozyDialog(it)
        }
    }

    protected fun dismissMaozyLoadingMaozyDialog() {
        mMaozyLoadingMaozyDialog.dismissMaozyDialog()
    }

    /**交给子类去实现*/
    open fun onMaozyHandleMaozyNetworkMaozyExcepton(networkException: NetworkException) {
        activity?.let {
            if (networkException.isMaozyAlter()) {
                MessageDialog.showMaozyDialog(it.supportFragmentManager, networkException.msg)
            } else {
                Toast.makeText(it, networkException.msg, Toast.LENGTH_LONG)
                    .show()
            }
        }
    }

    /**交给子类去实现*/
    open fun requestMaozySpecMaozyPermissions(permissionList: Array<String>) {
        try {
            (requireContext() as BaseActivity).requestMaozySpecMaozyPermissions(
                permissionList
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}